package com.group3.admin.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.group3.admin.service.IAMerchantService;
import com.group3.admin.service.impl.AMerchantServiceImpl;
import com.group3.entity.AMerchant;

/**
 * Servlet implementation class ImageServlet
 */
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      private IAMerchantService iAMerchantService = new AMerchantServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//				response.getWriter().append("Served at: ").append(request.getContextPath());
				String mId = request.getParameter("mId");
				String pictureType = request.getParameter("pictureType");
//				System.out.println("mId and picture "+mId + " " + pictureType );
				AMerchant aMerchant = iAMerchantService.queryAMerchantByMId(mId);
				// pictureType 表示 图片为身份证还是头像
				Base64 base64=new Base64();
				byte[] pictureBytes = null;
				if ("image".equals(pictureType)) {			// 头像
					String pictureBase64 = aMerchant.getmImage();
					pictureBytes =  pictureBase64.getBytes();
					pictureBytes = base64.decode(pictureBytes);
				} else if ("idCard".equals(pictureType)) {			// 身份证
					String pictureBase64 = aMerchant.getIdCard();
					pictureBytes =  pictureBase64.getBytes();
					pictureBytes = base64.decode(pictureBytes);			
				} else {			// 不合法类型
					System.out.println("Invalid Picture Type. Neither a avatar or id card!");
				}
				
				// 传二进制流 图片
				if (pictureBytes != null) {
					response.setContentType("image/jpeg");
					response.getOutputStream().write(pictureBytes);
				}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
